// 加载地图数据
function loadAreaData(bdMap) {
	$.ajax({
		url : "/flight/loadAreaLable",
		//async : false,
		success : function(dd) {
			var data = dd;
			// map
			for (var i = 0; i < data.length; i++) {
				var city = new BMap.Marker(new BMap.Point(data[i].lng, data[i].lat), {
					icon : new BMap.Symbol(BMap_Symbol_SHAPE_CIRCLE, {
						scale : 3,
						fillColor : '#E60000',
						fillOpacity : 1,
						strokeColor : '#fff',
						strokeWeight : 1
					// 线宽
					})
				});
				city.setTitle(data[i].city);
				city.setTop(false);

				var lable = new BMap.Label(data[i].city);
				lable.setStyle({
					color : "white",
					fontSize : "8px",
					textShadow : "2PX 2PX 2PX #000",
					backgroundColor : "rgba(0, 0, 0, 0)",
					border : '0'
				});
				lable.setOffset(new BMap.Size(13, -3));
				city.setLabel(lable);
				if (data[i].level != 1) {
					city.hide();
				}

				bdMap.addOverlay(city);
				// 设置全局变量数值
				GL_AREA_MAP.put(data[i].city, data[i]);
				GL_AREA_SYMBOL_MAP.put(data[i].city, city);
			}
		}
	});
	
}

// 显示数据
function showCity(obj) {
	var level = obj.prop('value');
	var checked = obj.is(':checked');
	GL_AREA_SYMBOL_MAP.each(function(key, value, index) {
		var dataLevel = GL_AREA_MAP.get(key).level;
		// console.log(dataLevel);
		if (dataLevel == level) {
			if (checked) {// 已经点击过的再点击，则隐藏
				value.show();
			} else {
				value.hide();
			}
		}
	});
}

// 航班列表
function FlightListControl() {
	// 默认停靠位置和偏移量
	this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
	this.defaultOffset = new BMap.Size(30, 30);
}
FlightListControl.prototype = new BMap.Control();
FlightListControl.prototype.initialize = function(map) {
	// 创建一个DOM元素
	var div = document.createElement("div");

	var tpl = '<div class=" control-panel-row"><h4>航班列表</h4></div>'
			+ '<div id="flights"></div>';
	// 添加文字说明
	div.id = 'flightList';
	div.className = 'row';
	div.innerHTML = tpl;
	div.style.cursor = "pointer";

	map.getContainer().appendChild(div);

	// 将DOM元素返回
	return div;
};

function loadFlightListAjax() {
	$.ajax({
		url : "/flight/loadFlightList",
		//async : false,
		success : function(dd) {

			var tmp = '';
			if (dd.length == 0) {
				tmp = '<div style="color:#fff;">查询不到航班信息</div>';
				var tbody = $('#flights');
				tbody.empty();
				tbody.append(tmp);
			} else {
				//console.log('load data ...');
				initData(dd);
				// 启动定时任务
				if(GL_GCTASK == null){
					GL_GCTASK = setInterval(runUpdateTask, 5000);
				}
			}
		}
	});
}

// 初始化数据
function initData(dd) {
	GL_PLANE_LIST_IDX = 0;
	GL_PLANE_MARQUE_IDX = 0;
	
	var tbody = $('#flights');
	var divContent = '';
	var tableHead = '<tr>     ' + '								<th>航班号</th>         '
			+ '								<th>线路</th>           ' + '								<th>起飞时间</th>       '
			+ '								<th>到达时间</th>       ' + '								<th>状态</th>          '
			+ '								<th>操作</th></tr>           ';

	tbody.empty();
	var batch =0;
	var batchSize = 5;
	for (var i = 0; i < dd.length; i++) {
		GL_PLANE_MAP.put(dd[i].flight_id, dd[i]);
		var flyTime = dd[i].fly_time!=null?dd[i].fly_time.toDate().format('MM-dd hh:mm'):'-';
		var landTime = dd[i].land_time!=null?dd[i].land_time.toDate().format('MM-dd hh:mm'):'-';
		var status = '';
		if (dd[i].status == 0) {// 待起飞
			status = '<font color="#ff6666">待起飞</font>';
		} else if (dd[i].status == 1) {// 飞行中
			status = '<font color="#0099cc">飞行中</font>';
		} else if (dd[i].status == 2) {// 降落
			status = '<font color="#99cc00">降落</font>';
		}		
		
		 divContent += '<tr><td onclick=clearPlainRunLine(' +dd[i].flight_id + ');>'; 
		 divContent +=  dd[i].flight_code + '</td>';
		 divContent += '<td>'+dd[i].from_airport + ' 到 ' + dd[i].to_airport + '</td>';
		 divContent += '<td>'+flyTime+ '</td>';
		 divContent += '<td>'+landTime+ '</td>';
		 divContent += '<td>' + status + '</td>';
		 divContent += '<td><a onclick="setPlainRunLine(' + dd[i].flight_id + ');"> <i class="fa fa-search" />轨迹</a>|' 
		 			+ '<a onclick=\"showInfo(' + dd[i].flight_id +');\"><i class="fa fa-table" />详情</a></td>';
		 divContent += '</tr>';
				 
		 batch++;
		 if(batch == batchSize){
			 var style = 'style="display:none;"';
				if (i == batchSize-1) {
					style = '';
				}
				var tmp = tableHead + divContent;
				divContent = '<table class="control-panel-table" id=\"planeList_div_'
						+ GL_PLANE_LIST_IDX
						+ '\" '
						+ style
						+ '>'
						+ tmp
						+ '</table>';
				tbody.append(divContent);
				divContent = '';
				GL_PLANE_LIST_IDX++;
				batch = 0;
		 }
		 
		
		// 初始化第一个航班的信息
		if (i == 0) {
			showInfo(dd[i].flight_id);
		}

		// 显示飞机坐标icon
		if (dd[i].position != null) {
			setPlaneOnMap(dd[i]);
		}
		// 初始化航线对象,数据延迟加载
		initPlaneLine(dd[i].flight_id,dd[i].from_gps);
	}	
	
	if(batch>0){//处理剩余行
		var tmp = tableHead + divContent;
		divContent = '<table class="control-panel-table" id=\"planeList_div_'
				+ GL_PLANE_LIST_IDX
				+ '\" '
				+ style
				+ '>'
				+ tmp
				+ '</table>';
		tbody.append(divContent);
		divContent = '';
	}
	
}


// 飞行信息
function showInfo(flightId) {
	$.ajax({
		url : "/flight/getFlightInfo",
		//async : false,
		data : {
			"flight_id" : flightId
		},
		success : function(dd) {

			var tmp = '<font class="flight-code">' + dd.flight_code + '</font>'
					+ '<font class="font-blue">' + dd.from_airport + ' 到 '
					+ dd.to_airport + '</font><br/>';

			// 乘机人数
			tmp += '<font>乘机人数:' + (dd.people != null ? dd.people : 0)
					+ '人</font><br/>';
			// 飞行时间
			var time = '-';
			if (dd.plan_land_time != null && dd.fly_time != null) {
				time = timeInterval(dd.fly_time.toDate(), dd.plan_land_time
						.toDate());
				tmp += '<font>预计飞行时间:' + time + '</font><br/>';
			}

			// 预计到达时间
			var t = '-';
			if (dd.plan_land_time != null) {
				t = dd.plan_land_time.toDate().format('yyyy-MM-dd hh:mm');
				tmp += '<font>预计到达时间:' + t + '</font>';
			}

			var flightContent = $('#flightContent');
			flightContent.empty();
			flightContent.append(tmp);
		}
	});

}

function timeInterval(startTime, endTime) {
	var planFlyTime = endTime - startTime;
	console.log(planFlyTime);
	// 计算出相差天数
	var days = Math.floor(planFlyTime / (24 * 3600 * 1000));

	// 计算出小时数
	var leave1 = planFlyTime % (24 * 3600 * 1000);// 计算天数后剩余的毫秒数
	var hours = Math.floor(leave1 / (3600 * 1000));

	// 计算相差分钟数
	var leave2 = leave1 % (3600 * 1000); // 计算小时数后剩余的毫秒数
	var minutes = Math.floor(leave2 / (60 * 1000));

	var time = '';
	if (days != 0) {
		time += days + '天 ';
	}
	time += hours + '小时 ' + minutes + '分钟';

	return time;
}

// 飞机信息面板切换
function marqueePlaneList() {
	 console.log(GL_PLANE_LIST_IDX+' '+GL_PLANE_MARQUE_IDX);
	if (GL_PLANE_MARQUE_IDX >= (GL_PLANE_LIST_IDX)) {
		$('#planeList_div_' + GL_PLANE_MARQUE_IDX).hide();
		$('#planeList_div_0').fadeIn();
		GL_PLANE_MARQUE_IDX = 0;
		
		setTimeout(1000);
		loadFlightListAjax();// 重新加载数据
	} else {
		var oldIdx = GL_PLANE_MARQUE_IDX;
		GL_PLANE_MARQUE_IDX++;
		$('#planeList_div_' + oldIdx).hide();
		$('#planeList_div_' + GL_PLANE_MARQUE_IDX).fadeIn();

	}
	marPlaneListTask = setTimeout(marqueePlaneList,speed);
}

// 显示飞机
function setPlaneOnMap(dd) {
	if(!GL_PLANE_SYMBOL_MAP.contain(dd.flight_id)){
		var pos = dd.position.split('|');
		var lng = pos[0];
		var lat = pos[1];
		var point = new BMap.Point(lng, lat);
		var _vectorPlane = new BMap.Marker(point, {
			// 初始化小飞机Symbol
			icon : new BMap.Symbol(BMap_Symbol_SHAPE_PLANE, {
				scale : 2,
				rotation : 0,
				fillColor : '#C6E2FF',
				fillOpacity : 1,
				strokeColor : '#555',
				strokeWeight : 1
			// 线宽
			})
		});

		// 设置飞机的title
		_vectorPlane.setTitle(dd.from_airport + '->' + dd.to_airport);

		// 飞机图标旋转角度
		var to_pos = dd.to_gps.split('|');
		var to_lng = to_pos[0];
		var to_lat = to_pos[1];
		var rotation = caluateRotation(lng, lat, to_lng, to_lat);
			_vectorPlane.setRotation(rotation);
		//console.log('setPlainOnMap>>'+lng+' '+lat+' '+to_lng+' '+to_lat+' '+rotation);
		GL_PLANE_SYMBOL_MAP.put(dd.flight_id, _vectorPlane);
		map.addOverlay(_vectorPlane);
		
		_vectorPlane.addEventListener('mouseover',function(){
			var line = GL_LINE_MAP.get(dd.flight_id);
			line.show();
		});
		
		_vectorPlane.addEventListener('mouseout',function(){
			var line = GL_LINE_MAP.get(dd.flight_id);
			line.hide();
		});
		
	}
	
}

function initPlaneLine(flightId,from_gps) {
	if(!GL_LINE_MAP.contain(flightId)){
		var points = [];
		var curve = new BMap.Polyline(points);
		if(from_gps !=null){	
			var gps = from_gps.split('|');
			var lng = gps[0];
			var lat = gps[1];
			//console.log('from_gps >> '+from_gps);
			curve.setPath([new BMap.Point(lng,lat)]);
			//console.log('setPath>>>'+JSON.stringify(curve.getPath()));
		}
		curve.setStrokeColor('#1E90FF');
		curve.setStrokeWeight(3);
		curve.hide();
		map.addOverlay(curve);
		GL_LINE_MAP.put(flightId, curve);// 初始化时候登记航线数据
	}
}

function showLine(flightId) {
	if (GL_LINE_SHOW_MAP.contain(flightId)) {
		//console.log('off');
		GL_LINE_SHOW_MAP.remove(flightId);
		GL_LINE_MAP.get(flightId).hide();
	} else {
		//console.log('');
		GL_LINE_SHOW_MAP.put(flightId, 0);
		GL_LINE_MAP.get(flightId).show();
	}
}

// 设置飞机运行轨迹
function setPlainRunLine(flightId) {
	if (GL_LINE_MAP.contain(flightId)) {
		var create_time='';
		if(GL_GPS_LASTTIME_MAP.contain(flightId)){
			create_time = GL_GPS_LASTTIME_MAP.get(flightId);
		}	
		
		$.ajax({
			url : "/flight/getGPSRecord",
			async : false,
			data : {
				"flight_id" : flightId,
				'create_time':create_time
			},
			success : function(dd) {
				var points = dd;
				if(points.length>0){
					GL_GPS_LASTTIME_MAP.put(flightId,points[points.length-1].create_time);//记录最后等级的时间
				}
				if (points != null && points.length > 0) {
					var line = GL_LINE_MAP.get(flightId);
					var tmp = line.getPath();
					console.log('points length>>>'+points.length);
					for (var i = 0; i < points.length; i++) {
						tmp.push(new BMap.Point(points[i].lng, points[i].lat));
					}
					console.log(JSON.stringify(tmp));
					line.setPath(tmp);
				}
				showLine(flightId);
			}
		});
		
		
		
	} else {
		console.log('flightId=[' + flightId + '] is not in GL_LINE_MAP');
	}
}

function clearPlainRunLine(flightId) {
	var line = GL_LINE_MAP.get(flightId);
	line.hide();
}

// 获取飞机GPS轨迹
function getGPSRecord(flightId) {
	var create_time = '';
	if(GL_GPS_LASTTIME_MAP.contain(flightId)){
		create_time = GL_GPS_LASTTIME_MAP.get(flightId);
	}	
	var myPoints = [];
	$.ajax({
		url : "/flight/getGPSRecord",
		async : false,
		data : {
			"flight_id" : flightId,
			'create_time':create_time
		},
		success : function(dd) {
			myPoints = dd;
			if(myPoints.length>0){
				GL_GPS_LASTTIME_MAP.put(flightId,myPoints[myPoints.length-1].create_time);//记录最后等级的时间
			}
			//console.log(JSON.stringify(myPoints));
		}
	});
	
	return myPoints;
}

function caluateRotation(cur_lng, cur_lat, to_lng, to_lat) {
	var len_y = to_lat-cur_lat;
	var len_x = to_lng-cur_lng;
	var tan_yx = Math.abs(len_y/len_x);
	
	var angle = 0;
	if(len_y>0&&len_x<0){
		angle=Math.atan(tan_yx)*180/Math.PI-90;
	}else if(len_y>0 &&len_x>0){
		angle=90-Math.atan(tan_yx)*180/Math.PI;
	}else if(len_y<0&&len_x<0){
		angle=-Math.atan(tan_yx)*180/Math.PI-90;
	}else if(len_y<0&&len_x>0){
		angle=Math.atan(tan_yx)*180/Math.PI+90;
	}
	return angle;
}

// GPS定时采集任务
function queryStatusTask() {
	GL_PLANE_MAP.each(function(key, value, index) {
		if(value.status == 2){
			$.ajax({
				url : "/flight/getPlaneStatus",
				//async : false,
				data : {
					"flight_id" : key
				},
				success : function(dd) {
					var status = dd.status;
					if(status == 9){// 转存
						//console.log('flight_id == '+key+' clearing...');	
						if(GL_PLANE_SYMBOL_MAP.contain(key)){
							var tmp = GL_PLANE_SYMBOL_MAP.get(key);
							map.removeOverlay(tmp);
							GL_PLANE_SYMBOL_MAP.remove(key);
						}
						
						if(GL_LINE_MAP.contain(key)){
							var tmp = GL_LINE_MAP.get(key);
							map.removeOverlay(tmp);
							GL_LINE_MAP.remove(key);
							GL_LINE_SHOW_MAP.remove(key);
							GL_GPS_LASTTIME_MAP.remove(key);
						}
						GL_PLANE_MAP.remove(key);
					}
				}
			});
				
		}
		
	});
	
	setTimeout(queryStatusTask,clearSpeed);
}

// 定时采集任务
function runUpdateTask() {
	// 循环
	GL_PLANE_MAP.each(function(key, value, index) {
		var flightId = key;	
		var create_time='';
		if(GL_GPS_LASTTIME_MAP.contain(flightId)){
			create_time = GL_GPS_LASTTIME_MAP.get(flightId);
		}	
		
		$.ajax({
			url : "/flight/getGPSRecord",
			//async : false,
			data : {
				"flight_id" : flightId,
				'create_time':create_time
			},
			success : function(dd) {
				var points = dd;
				if(points.length>0){
					GL_GPS_LASTTIME_MAP.put(flightId,points[points.length-1].create_time);//记录最后等级的时间
				}
				var len = points.length;
				if (len > 0) {// 存在轨迹数据
					// 获取飞机坐标
					var curLocate = new BMap.Point(points[len - 1].lng,
							points[len - 1].lat);
					var planeIcon = GL_PLANE_SYMBOL_MAP.get(key);
					planeIcon.setPosition(curLocate);

					// 设置飞机旋转角度
					var planeInfo = GL_PLANE_MAP.get(key);
					var to_pos = planeInfo.to_gps.split('|');
					var to_lng = to_pos[0];
					var to_lat = to_pos[1];
					var rot = caluateRotation(points[len - 1].lng, points[len - 1].lat,
							to_lng,to_lat);
					planeIcon.setRotation(rot);
					//console.log('runUpdateTask>>'+points[len - 1].lng+' '+points[len - 1].lat+' '+to_lng+' '+to_lat+' '+rot);
					// 更新航线数据
					var line = GL_LINE_MAP.get(key);
					var tmp = line.getPath();
					//console.log('getPath >> '+JSON.stringify(tmp)+' & '+points.length);
					console.log('update >>'+points.length+'&'+JSON.stringify(tmp));
					for (var i = 0; i < points.length; i++) {
						tmp.push(new BMap.Point(points[i].lng, points[i].lat));
					}
					line.setPath(tmp);
					if (GL_LINE_SHOW_MAP.contain(key)) {// 存在等级则打开展示记录
						line.show();
					}
				}
			}
		});
	});
}

// 航班信息
function FlightInfoControl() {
	// 默认停靠位置和偏移量
	this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
	this.defaultOffset = new BMap.Size(30, 300);
}

FlightInfoControl.prototype = new BMap.Control();

FlightInfoControl.prototype.initialize = function(map) {
	// 创建一个DOM元素
	var div = document.createElement("div");

	var tpl = '<div class="control-panel-row flightInfoTitle"><h4>航班实时信息</h4></div>'
			+ '<div id="flightInfoContainer"><div id="flightContent"></div></div>';
	// 添加文字说明
	div.id = 'flightInfo';
	div.className = 'box';
	div.innerHTML = tpl;
	// 设置样式
	div.style.cursor = "pointer";
	// div.style.border = "1px solid gray";

	map.getContainer().appendChild(div);
	// 将DOM元素返回
	return div;
}

function CityControl() {
	// 默认停靠位置和偏移量
	this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;
	this.defaultOffset = new BMap.Size(30, 30);
}

CityControl.prototype = new BMap.Control();

CityControl.prototype.initialize = function(map) {
	// 创建一个DOM元素
	var div = document.createElement("div");

	var tpl = '<div class="control-panel-row cityControlDiv">'
			+ '<div class="cityShowTitle"><a class="fa fa-plane"></a>显示城市座标</div>'
			+ '<div class="cityCheckBox"><input id="level1Citys"type="checkbox" value="1" >一级城市 '
			+ '<input type="checkbox" id="level2Citys" value="2">二级城市</div>'
			+ '</div>';
	// 添加文字说明
	div.id = 'cityControl';
	div.className = 'box';
	div.innerHTML = tpl;
	// 设置样式
	div.style.cursor = "pointer";
	map.getContainer().appendChild(div);
	// 将DOM元素返回
	return div;
}

var rDrag = {
	o : null,
	// 欢迎来到站长特效网，我们的网址是www.zzjs.net，很好记，zz站长，js就是js特效，本站收集大量高质量js代码，还有许多广告代码下载。
	init : function(o) {
		o.onmousedown = this.start;
	},
	start : function(e) {
		var o;
		e = rDrag.fixEvent(e);
		e.preventDefault && e.preventDefault();
		rDrag.o = o = this;
		o.x = e.clientX - rDrag.o.offsetLeft;
		o.y = e.clientY - rDrag.o.offsetTop;
		document.onmousemove = rDrag.move;
		document.onmouseup = rDrag.end;
	},
	move : function(e) {
		e = rDrag.fixEvent(e);
		var oLeft, oTop;
		oLeft = e.clientX - rDrag.o.x;
		oTop = e.clientY - rDrag.o.y;
		rDrag.o.style.left = oLeft + 'px';
		rDrag.o.style.top = oTop + 'px';
	},
	end : function(e) {
		e = rDrag.fixEvent(e);
		rDrag.o = document.onmousemove = document.onmouseup = null;
	},
	fixEvent : function(e) {
		if (!e) {
			e = window.event;
			e.target = e.srcElement;
			e.layerX = e.offsetX;
			e.layerY = e.offsetY;
		}
		return e;
	}
}
